<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { createOrder } from '@/services/order.js'
import { listAddresses } from '@/services/address.js'

const router = useRouter()

// 表单数据
const receiveName = ref('')
const receivePhone = ref('')
const receiveAddress = ref('')
const payType = ref('ALIPAY')
const remark = ref('')

// 订单商品列表
const productList = ref([])

// 地址相关
const addressList = ref([])
const selectedAddressId = ref('')

// 计算总价
const totalPrice = computed(() => {
  return productList.value.reduce((sum, item) => {
    return sum + (item.price || 0) * (item.quantity || 1)
  }, 0)
})

// 初始化时从localStorage获取订单参数和从API获取地址列表
onMounted(async () => {
  try {
    // 获取订单参数
    const pendingOrder = localStorage.getItem('pendingOrder')
    if (pendingOrder) {
      const orderData = JSON.parse(pendingOrder)
      
      // 设置商品列表
      productList.value = orderData.productList || []
      
      // 暂不设置表单字段的默认值，优先使用地址列表的数据
      // if (orderData.receiveName || orderData.receivePhone || orderData.receiveAddress) {
      //   receiveName.value = orderData.receiveName || ''
      //   receivePhone.value = orderData.receivePhone || ''
      //   receiveAddress.value = orderData.receiveAddress || ''
      //   payType.value = orderData.payType || 'ALIPAY'
      //   remark.value = orderData.remark || ''
      // }
    }
  } catch (e) {
    console.error('获取订单参数失败:', e)
  }
  
  // 获取地址列表
  try {
    const response = await listAddresses()
    
    // 标准化地址列表数据
    if (response && response.data) {
      // 处理可能的不同数据结构
      const rawData = Array.isArray(response.data) ? response.data : (response.data.list || [])
      
      // 检查原始数据是否有内容
      if (rawData && rawData.length > 0) {
        
        // 转换并标准化地址数据
        addressList.value = rawData.map(item => ({
          id: item.id || item.addressId,
          receiver: item.receiver || item.name || item.consignee,
          phone: item.phone || item.tel || item.mobile,
          address: item.address || item.detailAddress || item.addressDetail
        })).filter(item => item.receiver && item.phone && item.address)
        

        
        // 设置第一个地址为默认值
        if (addressList.value.length > 0) {
          const defaultAddress = addressList.value[0]
          setAddress(defaultAddress)
          selectedAddressId.value = defaultAddress.id || ''
        }
      } else {
  
      }
    } else {
  
    }
  } catch (e) {
    console.error('获取地址列表失败:', e)
    // 只在API调用失败时显示错误，不自动使用模拟数据
  }
})

// 设置选中的地址信息
function setAddress(address) {
  if (address) {
    // 尝试更多可能的字段名以适应不同的API响应格式
    receiveName.value = address.receiver || address.name || address.receiveName || address.consignee || ''
    receivePhone.value = address.phone || address.tel || address.receivePhone || address.mobile || ''
    receiveAddress.value = address.address || address.detailAddress || address.receiveAddress || address.addressDetail || ''
  }
}

// 处理地址选择变更
function handleAddressChange() {
  const selectedAddress = addressList.value.find(addr => addr.id === selectedAddressId.value)
  if (selectedAddress) {
    setAddress(selectedAddress)
  }
}

// 提交订单
async function submitOrder() {
  try {
    // 验证表单
    if (!receiveName.value.trim()) {
      alert('请输入收货人')
      return
    }
    if (!receivePhone.value.trim()) {
      alert('请输入手机号')
      return
    }
    if (!receiveAddress.value.trim()) {
      alert('请输入收货地址')
      return
    }
    if (productList.value.length === 0) {
      alert('订单中没有商品')
      return
    }
    
    // 构建订单参数，包含后端接口所需的字段
    const orderParams = {
      productList: productList.value.map(item => ({
        productId: item.productId || item.id || item.skuId || 0,
        buyQuantity: item.quantity || item.qty || 1
      })),
      receiveName: receiveName.value.trim(),
      receivePhone: receivePhone.value.trim(),
      receiveAddress: receiveAddress.value.trim(),
      payType: payType.value,
      remark: remark.value.trim(),
      // 以下字段通常由后端生成，但如果接口要求前端提供，这里可以进行设置
      // orderId: 通常由后端生成，前端可不提供
      // orderNo: 通常由后端生成，前端可不提供
      // 订单总金额，使用计算的总价
      totalAmount: totalPrice.value,
      // 实付金额，默认与总金额相同
      payableAmount: totalPrice.value,
      // payUrl: 通常由后端生成并返回
      // expireTime: 通常由后端设置并返回
    }
    

    
    // 调用创建订单接口
    const result = await createOrder(orderParams)
    

    
    // 订单成功后清除localStorage中的订单数据
    localStorage.removeItem('pendingOrder')
    
    // 显示成功消息并跳转到订单列表页
    alert('订单创建成功！')
    router.push('/orders')
  } catch (error) {
    console.error('订单创建失败:', error)
    alert('订单创建失败，请重试')
  }
}
</script>

<template>
  <div class="container checkout">
    <h2>填写收货信息</h2>
    

    <div class="order-products" v-if="productList.length > 0">
      <h3>订单商品</h3>
      <div class="product-list">
        <div class="product-item" v-for="item in productList" :key="item.productId">
          <img v-if="item.productImage" :src="item.productImage" :alt="item.productName" class="product-image" />
          <div class="product-info">
            <div class="product-name">{{ item.productName }}</div>
            <div class="product-price">￥{{ (item.price || 0).toFixed(2) }} x {{ item.quantity || 1 }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <form class="form">
      <!-- 地址选择下拉框 -->
      <div class="form-group" v-if="addressList.length > 0">
        <label>选择收货地址</label>
        <select 
          v-model="selectedAddressId" 
          @change="handleAddressChange"
          class="form-select"
        >
          <option value="">请选择地址</option>
          <option 
            v-for="address in addressList" 
            :key="address.id" 
            :value="address.id"
          >
            {{ address.receiver || address.name }} {{ address.phone || address.tel }} {{ address.address || address.detailAddress }}
          </option>
        </select>
      </div>
      
      <div class="form-group">
        <label>收货人</label>
        <input 
          v-model="receiveName" 
          placeholder="请输入收货人姓名"
          class="form-input"
        />
      </div>
      
      <div class="form-group">
        <label>手机号</label>
        <input 
          v-model="receivePhone" 
          placeholder="请输入手机号"
          type="tel"
          class="form-input"
        />
      </div>
      
      <div class="form-group">
        <label>收货地址</label>
        <textarea 
          v-model="receiveAddress" 
          placeholder="请输入详细收货地址"
          class="form-textarea"
          rows="3"
        ></textarea>
      </div>
      
      <div class="form-group">
        <label>支付方式</label>
        <select v-model="payType" class="form-select">
          <option value="ALIPAY">支付宝</option>
          <option value="WECHAT">微信支付</option>
          <option value="CASH">货到付款</option>
        </select>
      </div>
      
      <div class="form-group">
        <label>备注</label>
        <input 
          v-model="remark" 
          placeholder="选填，请输入订单备注"
          class="form-input"
        />
      </div>
    </form>
    
    <div class="summary">
      <div class="total-price">
        应付金额：<b class="price">￥{{ totalPrice.toFixed(2) }}</b>
      </div>
      <button class="submit-btn" @click="submitOrder">
        提交订单
      </button>
    </div>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.checkout {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.checkout h2 {
  margin-bottom: 24px;
  font-size: 20px;
  color: #333;
}

.checkout h3 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.order-products {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.product-price {
  font-size: 14px;
  color: #ff4d4f;
}

.form {
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-input,
.form-textarea,
.form-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.total-price {
  font-size: 16px;
  color: #333;
}

.price {
  color: #ff4d4f;
  font-size: 20px;
  font-weight: bold;
}

.submit-btn {
  padding: 12px 24px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-btn:hover {
  background-color: #40a9ff;
}

.submit-btn:active {
  background-color: #096dd9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .checkout {
    padding: 16px;
  }
  
  .summary {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .submit-btn {
    width: 100%;
  }
}
</style>


